package com.chalk.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.chalk.common.constant.CommonConstants;
import com.chalk.common.exception.ServiceException;
import com.chalk.common.util.ResultCode;
import com.chalk.config.security.JwtRedisUtil;
import com.chalk.config.security.JwtTokenUtils;
import com.chalk.config.security.SecurityPasswordUtil;
import com.chalk.dao.MemberDao;
import com.chalk.model.Member;
import com.chalk.model.SysUser;
import com.chalk.service.MemberService;
import com.chalk.service.SysUserService;
import com.chalk.vo.MemberVo;
import com.chalk.vo.MyMemberVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 会员表(Member)表服务实现类
 *
 * @author maxiaoqiang
 * @since 2019-03-22 17:38:23
 */
@Service
@Transactional
@Slf4j
public class MemberServiceImpl extends ServiceImpl<MemberDao, Member> implements MemberService {

    @Autowired
    private MemberDao memberDao;
    @Autowired
    private JwtRedisUtil jwtRedisUtil;

    @Autowired
    private SysUserService sysUserService;

    /*自定义接口*/

    /**
     * 根据主键批量(逻辑)删除
     *
     * @param ids
     * @return
     */
    @Override
    public int deleteBatchByPrimaryKey(String[] ids) {
        return memberDao.deleteBatchByPrimaryKey(ids);
    }


    @Override
    public Member selectUserDetail(HttpServletRequest request) {
        String header = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
        if (StringUtils.isBlank(header)) {
            return null;
        }
        String token = header.replace(JwtTokenUtils.TOKEN_PREFIX, "");
        String phone = JwtTokenUtils.getUsername(token);
        Member member = super.selectOne(new EntityWrapper<Member>().eq("mobile_phone", phone).or().eq("open_id", phone));
        log.info("-------------------删除操作人-----------------{}", JSONObject.toJSONString(member));
        return member;
    }

    @Override
    public boolean updateMemberPwd(MemberVo memberVo) {
        Member member = super.selectById(memberVo.getMemberId());
        if (member == null) {
            throw new ServiceException(ResultCode.USER_NOT_FOUND);
        }
        if (!SecurityPasswordUtil.decrypt(memberVo.getOldPwd(), SecurityPasswordUtil.BCRYPT + member.getPassword())) {
            throw new ServiceException(ResultCode.OLD_PWD_ERROR);
        }
        if (memberVo.getNewPwd().length() <= CommonConstants.APP_USER_PWD_MIN_LEN) {
            throw new ServiceException(ResultCode.PWD_LEN_ERROR);
        }
        if (SecurityPasswordUtil.decrypt(memberVo.getNewPwd(), SecurityPasswordUtil.BCRYPT + member.getPassword())) {
            throw new ServiceException(ResultCode.PWD_SAME);
        }
        member.setPassword(SecurityPasswordUtil.encrypt(memberVo.getNewPwd()));
        member.setUpdateTime(DateUtil.date());
        return super.updateById(member);

    }

    @Override
    public Member getMemberByMobilePhone(String mobilePhone) {
        if (mobilePhone == null) {
            throw new ServiceException(ResultCode.PARAM_IS_BLANK);
        }
        return memberDao.getMemberByMobilePhone(mobilePhone);
    }

    @Override
    public Page<Member> getMyMembers(MyMemberVo myMemberVo, Member member) {
        //排序的列
        List<String> descs = new ArrayList<>();
        descs.add("orderNum");
        Integer page = myMemberVo.getPage();
        if (page == null) {
            page = 1;
        }
        Integer size = myMemberVo.getSize();
        if (size == null) {
            size = 10;
        }

        Page<Member> dtoPage = new Page<Member>(page, size);
        dtoPage.setDescs(descs);

        return dtoPage.setRecords(this.baseMapper.getMyMembers(dtoPage, myMemberVo, getMyMemberIds(member)));
    }

    @Override
    public Page<Member> getMembersByShopId(Page<Member> page, Map<String, Object> map) {
        //降序
        List<String> descs = new ArrayList<>();
        descs.add("t.create_time");

        page.setDescs(descs);


        return page.setRecords(this.baseMapper.getMembersByShopId(page, map));
    }

    @Override
    public List<String> getMyMemberIds(Member member) {
        List<String> memberIds = new ArrayList<String>();//存储客户ID
        //一级分销商
        if (member.getDistributorId() != null && member.getDistributorId().equals("1")) {
            List<Member> members = this.selectList(new EntityWrapper<Member>().eq("reference_id", member.getMemberId()));

            for (Member m : members) {
                if (m.getDistributorId() != null && m.getDistributorId().equals("2")) {
                    List<Member> ms = this.selectList(new EntityWrapper<Member>().eq("reference_id", m.getMemberId()));
                    for (Member m2 : ms) {
                        memberIds.add(m2.getMemberId());
                    }
                }
                memberIds.add(m.getMemberId());

            }


        }
        //二级分销商
        else if (member.getDistributorId() != null && member.getDistributorId().equals("2")) {
            List<Member> ms = this.selectList(new EntityWrapper<Member>().eq("reference_id", member.getMemberId()));
            for (Member m2 : ms) {
                memberIds.add(m2.getMemberId());
            }
        }


        return memberIds;
    }


    @Override
    public Member getInfoByMemberId(String memberId) {
        return this.baseMapper.getInfoByMemberId(memberId);
    }


    @Override
    public String getSellerId(Member member) {
        //获取分销员
        Member d = baseMapper.selectById(member.getReferenceId());

        //获取区域商
        Member q = baseMapper.selectById(d.getReferenceId());

        //获取系统用户
        SysUser sysUser = sysUserService.selectOne(new EntityWrapper<SysUser>().eq("member_id", q.getMemberId()));

        return sysUser.getSellerId();
    }

    @Override
    public Member getShopMember(Member member) {
        Member m = selectOne(new EntityWrapper<Member>().eq("new_shop_id", member.getNewShopId()).eq("member_type", 3));
        return m;
    }

    @Override
    public Boolean updateIntegral(Integer integral, String type,String memberId) {
        Member member=selectById(memberId);
        if(type.equals("add")){
            //增加积分
            member.setIntegral(member.getIntegral().intValue()+integral.intValue());
        }
        if(type.equals("reduce")){
            //减少积分
            member.setIntegral(member.getIntegral().intValue()-integral.intValue());
        }
        return updateById(member);
    }
}